// Copyright 2010 Google Inc. All Rights Reserved.

/**
 * @fileoverview Request polling.
 *
 * @author monsur@google.com (Monsur Hossain)
 */

goog.provide('googleapis.Poll');


/**
 * @constructor
 */
googleapis.Poll = function() {
  this.batch_ = new googleapis.Batch();
  this.interval_ = 10000;
  this.timeoutId_ = null;
};


/**
 * @param {string} key A unique key to identify this request.
 * @param {Object} request The request object.
 * @param {Function} callback The function to call with the response.
 * @return {googleapis.Poll} This object.
 */
googleapis.Poll.prototype.add = function(key, request, callback) {
  this.batch_.add(key, request, callback);
  return this;
};


/**
 * @param {number} interval The polling interval in seconds.
 */
googleapis.Poll.prototype.setInterval = function(interval) {
  this.interval_ = interval * 1000;
};


/**
 * @param {Function} callback The function to call on any batch responses that
 *     don't have an individual callback.
 */
googleapis.Poll.prototype.execute = function(callback) {
  if (this.timeoutId_) {
    throw new Error('Polling has already started.');
  }

  var that = this;
  var executeHelper = function() {
    that.batch_.execute(callback);
    that.timeoutId_ = window['setTimeout'](function() {
        executeHelper();
      }, that.interval_);
  };

  executeHelper();
};


/**
 * Cancels the current polling request.
 */
googleapis.Poll.prototype.cancel = function() {
  if (this.timeoutId_) {
    window['clearTimeout'](this.timeoutId_);
    this.timeoutId_ = null;
  }
};
